<template>
  <el-form ref="userRuleFormRef" v-model="userRuleForm" label-width="auto" :inline="true">
    <el-form-item label="用户ID" prop="userId">
      <el-input v-model.trim="userRuleForm.userId" placeholder="请输入用户ID" />
    </el-form-item>
    <el-form-item label="用户名称" prop="userName">
      <el-input v-model.trim="userRuleForm.userName" placeholder="请输入用户名称" />
    </el-form-item>
    <el-form-item label="用户状态" prop="state">
      <el-select v-model="userRuleForm.state" placeholder="请输入用户状态">
        <el-option :label=item.label :value=item.value v-for="item in options" />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(userRuleFormRef)">
        查询
      </el-button>
      <el-button @click="resetForm(userRuleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
  <div>
    <el-button type="primary" @click="handleAdd" v-has="'user-add'">新增</el-button>
    <el-button type="danger" @click="handleAllDelete"  v-has="'user-allDelete'">批量删除</el-button>
    <el-button type="success" @click="handleExcel" v-has="'user-export'">导出数据</el-button>
  </div>
  <div>
    <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column :label="item.label" :prop="item.property" :formatter="item.formatter"
        v-for="(item, t) in columns" :key="t" />
      <el-table-column align="center" label="操作">
        <template #default="scope">
          <el-button size="small" @click="handleUpdate(scope.row)" v-has="'user-update'" v-if="scope.row.state === 2">恢复</el-button>
          <el-button size="small" @click="handleEdit(scope.row)" v-has="'user-edit'">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)" v-has="'user-delete'">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div class="demo-pagination-block">
    <div class="demonstration">All combined</div>
    <el-pagination v-model:current-page="pager.currentPage" v-model:page-size="pager.pageSize" :page-sizes="[1,3,5,7,10]"
      :size="size" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
      :total="pager.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>
  <el-dialog v-model="dialogVisible" :title="active == 'add' ? '新增表单' : '编辑表单'" width="35%" draggable
    @close="closeDialog">
    <div>
      <el-form ref="DialogRuleFormRef" style="max-width: 600px" :model="DialogRuleForm" :rules="rules"
        label-width="auto">
        <el-form-item label="用户" prop="userName">
          <el-input v-model="DialogRuleForm.userName" placeholder="请输入您的用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input v-model="DialogRuleForm.userEmail" placeholder="请输入您的邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="DialogRuleForm.mobile" placeholder="请输入您的手机号" />
        </el-form-item>
        <el-form-item label="岗位" prop="job">
          <el-input v-model="DialogRuleForm.job" placeholder="请输入您的岗位" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select v-model="DialogRuleForm.state" placeholder="请输入您的状态">
            <el-option :label="item.label" :value="item.value" v-for="item in dialogoptions" :key="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="系统角色" prop="roleList">
          <el-select v-model="DialogRuleForm.roleList" multiple placeholder="请选择" style="width: 240px">
            <el-option v-for="(item, index) in options1" :key="index" :label="item.roleName" :value="item._id" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-cascader :options="options2" :props="props" v-model="DialogRuleForm.deptId" clearable />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="operateForm(DialogRuleFormRef)">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { nextTick, onMounted, reactive, ref } from 'vue'
import { type FormInstance, type FormRules } from 'element-plus'
import Api from './../api/index';
import { ElMessage, ElMessageBox } from 'element-plus'

// 表单数据
const options = [
  { value: 0, label: '所有' },
  { value: 1, label: '在职' },
  { value: 2, label: '离职' },
  { value: 3, label: '试用期' }
]
//form
const userRuleFormRef = ref<FormInstance>()
const userRuleForm = reactive<RuleForm>({
  userId: '',
  userName: '',
  state: 1,
})
//获取表单列表数据
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  getUsersList()
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// user操作按钮
const dialogVisible = ref(false)
const active = ref('add')
//新增
const handleAdd = () => {
  dialogVisible.value = true
  active.value = 'add'
}
//编辑删除所有
const handleAllDelete = (e: any) => {
  console.log(e);
  ElMessageBox.confirm(
    '你确定要删除这些数据吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      Api.getDeleteListAPI({ userIds: arr.value }).then((res) => {
        if (res) {
          getUsersList()
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
        }
      })

    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      })
    })
}

//导出数据
const handleExcel = () => {
  Api.getExcelAPI().then((res: any) => {
    console.log(res);
    const uploadExcel = (fileName:any) => {
      let length = res.data.length
      let buf = new ArrayBuffer(length)
      let view = new Uint8Array(buf)
      for (let i = 0;i<length; i++) {
         view[i] = res.data[i]
      }
      let blob:any = new Blob([buf])
      let url = URL.createObjectURL(blob)
      const aLink = document.createElement("a");
      aLink.setAttribute('downLoad',fileName)
      aLink.setAttribute('href',url)
      document.body.appendChild(aLink)
      console.log(document.body);
      aLink.click()
      document.body.removeChild(aLink)
      URL.revokeObjectURL(blob);
    }
    uploadExcel("myfile.xlsx")
  });
};

//table
interface User {
  userId: number | string
  date: string
  name: string
  address: string
}
//编辑
const handleEdit = (row: User) => {
  console.log(row)
  active.value = 'edit'
  // 这里需要用异步处理一下，避免bug
  nextTick(() => {
    // 把数据整合，使点击编辑可以拿到该数据
    Object.assign(DialogRuleForm, row)
  })
  dialogVisible.value = true
}
//单个删除处理
const handleDelete = (row: User) => {
  console.log(row)
  ElMessageBox.confirm(
    '你确定要删除这个数据吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      Api.getDeleteListAPI({ userIds: row.userId }).then((res) => {
        if (res) {
          getUsersList()
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
        }
      })

    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      })
    })
}
//恢复被删除到离职库
const handleUpdate = (row: User) => {
  console.log(row)
  ElMessageBox.confirm(
    '你确定要恢复这个数据吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      Api.getUpdateListAPI({ userIds: row.userId }).then((res) => {
        if (res) {
          getUsersList()
          ElMessage({
            type: 'success',
            message: '恢复成功',
          })
        }
      })

    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      })
    })
}
//关闭表单重置表单信息
const closeDialog = () => {
  resetForm(DialogRuleFormRef.value)
}
const tableData = ref<User[]>([])
//选择框
let arr = ref<any>([])
const multipleSelection = ref([])
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val
  console.log(multipleSelection.value);
  arr.value = multipleSelection.value.map((v: any) => {
    return v.userId
  })
}
const columns = [{
  label: '用户ID',
  property: 'userId',
  width: '100px'
},
{
  label: '用户名称',
  property: 'userName'
},
{
  label: '用户邮箱',
  property: 'userEmail'
},
{
  label: '用户角色',
  property: 'role',
  formatter: function (_row: any, _columns: any, cellValue: string | number, _index: any) {
    const obj: interTable = {
      0: '管理员',
      1: '普通用户'
    }
    return obj[cellValue]
  }
},
{
  label: '用户状态',
  property: 'state',
  //@ts-ignore
  formatter: function (row, columns, cellValue, index) {
    const obj: interTable = {
      0: '所有',
      1: '在职',
      2: '离职',
      3: '试用期'
    }
    return obj[cellValue]
  }
},
{
  label: '注册时间',
  property: 'createTime'
},
{
  label: '最后登录时间',
  property: 'lastLoginTime'
}
]

//分页
import type { ComponentSize } from 'element-plus'
const pager = ref({
  currentPage: 1,
  pageSize: 10,
  total:10
})
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)

// 分页大小变化
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  pager.value.pageSize = val
  getUsersList()
}
//分页页数变化
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  pager.value.currentPage = val
  getUsersList()
}

const dialogoptions = [
  { value: 1, label: '在职' },
  { value: 2, label: '离职' },
  { value: 3, label: '试用期' }
]

const DialogRuleFormRef = ref<FormInstance>()
const DialogRuleForm = reactive<DialogRuleForm>({
  userName: '',
  userEmail: '',
  mobile: '',
  job: '',
  state: 1,
  roleList: '',
  deptId: ''
})
//表单的新增或编辑，连接后端
const operateForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate()
  let params: any = DialogRuleForm
  params.active = active.value
  Api.getOperateListAPI(params).then(res => {
    if (res) {
      dialogVisible.value = false
      getUsersList()
    }
  })

};

//自定义表单校验
const validateMobile = (_rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入正确的手机号码'))
  } else if (/^1[3-9]\d{9}$/.test(value)) {
    callback()
  } else {
    callback(new Error('手机号码格式不对'))
  }
}

const rules = reactive<FormRules<DialogRuleForm>>({
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 10, message: '用户名长度为2-10之间', trigger: 'blur' },
  ],
  mobile: [
    {
      required: true,
      validator: validateMobile
    },
  ],
  state: [
    {
      required: true,
      message: '请输入您的状态',
      trigger: 'blur',
    },
  ],
})
//select选择器
const options1: any = ref([])

//部门联级选择
const props = {
  checkStrictly: true,
  label: 'deptName',
  value: '_id'
}
const options2 = ref([])
//请求
//用户数据请求
const getUsersList = async () => {
  const params = {
    ...userRuleForm,
    ...pager.value
  }
  const res: any = await Api.getUsersListAPI(params);
  console.log("user", res);
  const { list, total } = res
  tableData.value = list
  pager.value.total = total
}
//系统角色数据请求
const getRolesList = async () => {
  const res: any = await Api.getRolesListAPI()
  console.log('role', res);
  options1.value = res.list
}
//部门数据请求
const getDeptList = async () => {
  const res: any = await Api.getDeptListAPI()
  console.log('dept', res);
  options2.value = res
}

onMounted(() => {
  getUsersList()
  getRolesList()
  getDeptList()
})
</script>

<style>
.el-select__input-wrapper.is-hidden {
  position: initial;
}
</style>
